﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using EraNet.Core;
using EraNet.Data;
using EraNet.Core.Model.Test;
using EraNet.Core.Model.SysManage;

using EraNet.Common;
using EraNet.Services.Account;
using EraNet.Services.Test;
using EraNet.Core.Model.Account;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using EraNet.Services.SysManage;
using EraNet.WebApp.AppCore;

namespace EraNet.WebApp.LMS
{
    public class TestController : LMSBasePage
    {
        #region Fields
        private readonly IExaminationService _examinationService;
        private readonly ISysCardsService _syscardsService;
        private readonly IDictionaryService _dictionaryService;
        private readonly ISysConfigService _sysconfigService;
        private readonly IStudyMenuService _studymenuService;
        private readonly IStudyVideoService _studyVideoService;
        private readonly IMemberService _memberService;
        private readonly IStudyLocusService _studyLocusService;
        #endregion

        #region Constructors
        public TestController(IExaminationService examinationService, IDictionaryService dictionaryService, ISysConfigService sysconfigService, ISysCardsService syscardsService, IStudyMenuService studymenuService, IStudyVideoService studyVideoService, IMemberService memberService,
            IStudyLocusService studyLocusService)
        {
            this._examinationService = examinationService;
            this._syscardsService = syscardsService;
            this._dictionaryService = dictionaryService;
            this._sysconfigService = sysconfigService;
            this._studymenuService = studymenuService;
            this._studyVideoService = studyVideoService;
            this._memberService = memberService;
            this._studyLocusService = studyLocusService;
        }
        #endregion

        #region Method
        #region 模拟练习
        public ActionResult Exam()
        {
            ViewBag.myTabId = "2";//标示tab
            #region  判断权限
            ViewBag.Member = _memberService.GetLoginMember();
            #endregion
            #region 获取配置的值
            var dic = _sysconfigService.GetConfigByKey(EraNet.Core.Model.Enum.LMSConfigs.Exam_Allot);
            #endregion
            IList<Examination> list = _examinationService.AllotExamination(dic.CfgVaule);
            return View(list);
        }

        //public ActionResult _ExamPage()
        //{
        //    #region 获取配置的值
        //    var dic =_sysconfigService.GetConfigByKey(Core.Model.Enum.LMSConfigs.Exam_Allot,Core.Model.Enum.ConfigType.LMS);
        //    #endregion
        //    IList<Examination> list = _examinationService.AllotExamination(dic.CfgVaule);
        //    return View(list);
        //}
        #endregion

        #region 仿真考试
        public ActionResult CertExam()
        {
            
            ViewBag.myTabId = "2";//标示tab
            #region 获取配置的值
            var dic = _sysconfigService.GetConfigByKey(Core.Model.Enum.LMSConfigs.Exam_Allot);
            #endregion
            IList<Examination> list = _examinationService.AllotExamination(dic.CfgVaule);

            ViewBag.Member = _memberService.GetLoginMember();
            return View(list);
        }
        #endregion

        #region 返回值
        public ActionResult exam_result()
        {
            var examIds = Request.Form["resultString"];
            string[] pard = examIds.Split(',');
            var m = _memberService.GetLoginMember();
            int score = 0;
            foreach (string exam in pard)
            {
                string[] ex = exam.Split('|');
                if (ex[3].ToLower() == "true")
                {
                    score++;
                }
            }
            #region 保存考试记录
            string Rmsg = "您本次考试未能通过，请继续努力！";
            var fs = _sysconfigService.GetConfigByKey(EraNet.Core.Model.Enum.LMSConfigs.Exam_CfgKeys);
            int fsx = 90;
            if (fs != null && fs.Creater == m.AccountName) fsx = Convert.ToInt32(fs.CfgVaule);
            if (score >= fsx)
            {
                ExaminationLogs logs = new ExaminationLogs();
                logs.CreateDate = DateTime.Now;
                logs.ExaminationType = 4;
                logs.ExamLogs = examIds;
                logs.Mark = Common.StrTools.RandomString(12, 0);
                logs.MemberId = m.Id;
                logs.SchoolId = m.SchoolID;
                logs.Score = score;
                _examinationService.InsertExamLogs(logs);
                Rmsg = "您本次的考试成绩已经提交给驾校，如符合考试要求，驾校会在随后通知您参加考试！";

            }
            #endregion
            ViewBag.Score = score;
            ViewBag.Message = Rmsg;
            return View();
        }
        #endregion
        #endregion

        #region Pages
        public ActionResult ExamSubmit()
        {
            return View();
        }
        #endregion

        public ActionResult CardManager()
        {

            //_syscardsService.InsertCards("10000000BJ", 10, 0, true);
            return View();
        }

        #region 理论培训

        /// <summary>
        /// 理论培训页面
        /// </summary>
        /// <returns></returns>
        public ActionResult VideoStudy()
        {
            ViewBag.myTabId = "1";//标示tab

            //获取登录的学员
            Member student = _memberService.GetLoginMember();
            if (student == null)
            {
                return RedirectToAction("MemberLogin", "Account");
            }

            //理论的栏目id
            int pid = 817;

            //获取指定的所有栏目
            List<StudyMenu> listMenu = _studymenuService.GetListByFunc(m => true);
            ViewBag.listMenu = listMenu;
            //获取栏目下的所有视频
            List<StudyVideo> listVideo = _studyVideoService.GetList(v => true);
            ViewBag.listVideo = listVideo;
            //生成栏目树
            //ViewBag.menuTree = CreateTree(listMenu, listVideo, pid, pid);
            ViewBag.menuTree = CreateTree(listMenu, listVideo, pid, 820);
            return View();
        }

        #region 后台拼树

        private StringBuilder sBuilder = new StringBuilder();

        /// <summary>
        /// 生成栏目树
        /// </summary>
        /// <param name="listMenu">理论的所有栏目</param>
        /// <param name="listVideo">栏目下的所有视频</param>
        /// <param name="rootId">根节点</param>
        /// <param name="pid">父id</param>
        /// <returns></returns>
        public string CreateTree(List<StudyMenu> listMenu, List<StudyVideo> listVideo, int rootId, int pid)
        {
            //判断栏目下有没有视频
            List<StudyVideo> listVidoSon = GetVideosByMenuId(listVideo, pid);
            if (listVidoSon != null)
            {
                sBuilder.Append("<ul>");

                foreach (var item in listVidoSon)
                {
                    sBuilder.Append("<li>");
                    sBuilder.Append("<span class='file'>");
                    string videoPath = ConfigurationManager.AppSettings["videoPath"] + item.Folder;
                    sBuilder.AppendFormat("<a href='{0}' colid='{1}' spid='{2}' title='{3}'>", Utility.MyEncode(videoPath), item.MenuId, item.Id, item.VideoTitle);
                    sBuilder.Append(Utility.GetSubString(item.VideoTitle, 16, ""));
                    sBuilder.Append("</a>");
                    sBuilder.Append("</span>");
                    sBuilder.Append("</li>");
                }
                sBuilder.Append("</ul>");
            }

            //判断该栏目是否有子栏目
            List<StudyMenu> listColumnSon = GetMenusByPid(listMenu, pid);
            if (listColumnSon != null)
            {
                //有子栏目
                if (rootId == pid)
                {
                    sBuilder.Append("<ul id='menuTreeList' class='filetree'>");
                }
                else
                {
                    sBuilder.Append("<ul>");
                }
                foreach (var item in listColumnSon)
                {
                    sBuilder.AppendFormat("<li class='closed' colid='{0}'>", item.MenuId);
                    sBuilder.AppendFormat("<span class='folder' colid='{0}' title='{1}'>", item.MenuId, item.MenuName);
                    sBuilder.Append(Utility.GetSubString(item.MenuName, 20, ""));
                    sBuilder.Append("</span>");
                    //递归
                    CreateTree(listMenu, listVideo, rootId, item.MenuId);
                    sBuilder.Append("</li>");
                }

                sBuilder.Append("</ul>");
            }

            return sBuilder.ToString();
        }

        /// <summary>
        /// 获取栏目下的子栏目
        /// </summary>
        /// <param name="listMenu">理论的所有栏目</param>
        /// <param name="pid">父id</param>
        /// <returns></returns>
        public List<StudyMenu> GetMenusByPid(List<StudyMenu> listMenu, int pid)
        {
            List<StudyMenu> list = listMenu.Where(m => m.ParentId == pid).ToList();
            if (list.Count == 0)
            {
                list = null;
            }
            return list;
        }

        /// <summary>
        /// 获取栏目下的视频
        /// </summary>
        /// <param name="listVideo">理论的所有视频</param>
        /// <param name="menuId">栏目id</param>
        /// <returns></returns>
        public List<StudyVideo> GetVideosByMenuId(List<StudyVideo> listVideo, int menuId)
        {
            List<StudyVideo> list = listVideo.Where(v => v.MenuId == menuId).ToList();
            if (list.Count == 0)
            {
                list = null;
            }
            return list;
        }

        #endregion

        #region 记录学习轨迹

        /// <summary>
        /// ajax向学习轨迹表中插入一条数据
        /// </summary>
        /// <param name="lmid">栏目id</param>
        /// <param name="spid">视频id</param>
        /// <param name="menuType">栏目类别</param>
        /// <returns></returns>
        public JsonResult AddStudyLocus(string lmid, string spid, string menuType)
        {
            if (lmid == "0" || spid == "0")
            {
                return Json(new { msg = "栏目id或者视频id为0" });
            }

            string result = "0";
            //获取登录的学员
            Member student = _memberService.GetLoginMember();
            if (student == null)
            {
                return Json(new { msg = "学员未登录" });
            }

            //根据用户id和视频id获取实体
            int sid = Convert.ToInt32(spid);
            StudyLocus model = _studyLocusService.GetEntity(sl => sl.VideoId == sid && sl.UserId == student.Id);
            if (model == null)
            {
                #region 没有该记录， 向数据库中插入一条记录

                model = new StudyLocus();
                model.EndTime = Convert.ToDateTime("2000-01-01");
                model.IpAddress = Request.UserHostAddress;
                model.IsPassed = 0;
                model.IsValid = 0;
                model.MenuId = Convert.ToInt32(lmid);
                model.MenuType = menuType;//这个要根据栏目来查询出最高一级的id
                model.RecordTime = "";
                model.StartTime = DateTime.Now;
                model.UserId = student.Id;
                model.VideoId = Convert.ToInt32(spid);
                model.VideoTime = "";

                _studyLocusService.AddEntity(model);
                #endregion
            }
            else
            {
                #region 没有结束时间，表示上次该视频没有记录完整

                if (model.EndTime.ToString("yyyy-MM-dd") == "2000-01-01")
                {
                    model.StartTime = DateTime.Now;
                    _studyLocusService.UpdateEntity(model);
                }

                #endregion
            }

            return Json(new { msg = result });
        }

        /// <summary>
        /// ajax修改学习轨迹表
        /// </summary>
        /// <param name="lmid">栏目id</param>
        /// <param name="spid">视频id</param>
        /// <param name="myFlag">是否开始计时：0→不计时、1→计时</param>
        /// <returns></returns>
        public JsonResult EditStudyLocus(string lmid, string spid, string myFlag)
        {
            //获取登录的学员
            Member student = _memberService.GetLoginMember();
            if (student == null)
            {
                return Json(new { msg = "学员未登录" });
            }

            //根据用户id和视频id获取实体
            int sid = Convert.ToInt32(spid);
            StudyLocus model = _studyLocusService.GetEntity(sl => sl.VideoId == sid && sl.UserId == student.Id);
            if (model != null)
            {
                //没有结束时间，表示上次该视频没有记录完整
                if (model.EndTime.ToString("yyyy-MM-dd") == "2000-01-01")
                {
                    model.EndTime = DateTime.Now;
                    TimeSpan ts = model.EndTime - model.StartTime;
                    string myTime = DoMyTime(Convert.ToInt32(ts.TotalSeconds));
                    model.RecordTime = myTime;

                    //更新数据
                    _studyLocusService.UpdateEntity(model);
                }
            }


            return Json(new { });
        }

        #endregion

        #region 处理时间

        /// <summary>
        /// 处理时间
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns></returns>
        public string DoMyTime(int time)
        {
            string strMniute = "00";//分
            string strSecond = "00";//秒
            if (time < 10)
            {
                strSecond = DoTime(time);
            }
            else if (time < 60)
            {
                strSecond = DoTime(time);
            }
            else
            {
                int minute = time / 60;
                int second = time % 60;

                strMniute = DoTime(minute);
                strSecond = DoTime(second);
            }

            return strMniute + ":" + strSecond;
        }

        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="time">数据</param>
        /// <returns></returns>
        public string DoTime(int time)
        {
            string result = "";
            if (time < 10)
            {
                result = "0" + time;
            }
            else
            {
                result = time.ToString();
            }
            return result;
        }

        #endregion

        #region 显示正在播放视频的栏目

        public JsonResult AjaxShowMenuName(string menuType, string lmid)
        {
            string result = "科目一";

            if (string.IsNullOrWhiteSpace(menuType) || string.IsNullOrWhiteSpace(lmid) || menuType == "0" || lmid == "0")
            {
                return Json(new { msg = "科目一 道路交通安全法律、法规和规章" });
            }
            int menuId = 818;//栏目id，默认科目一
            //判断科目
            switch (menuType)
            {
                case "1":
                    result = "科目一";
                    menuId = 818;
                    break;
                case "2":
                    result = "科目二";
                    menuId = 819;
                    break;
                case "3":
                    result = "科目三";
                    menuId = 820;
                    break;
            }

            //获取当前栏目下的直接子栏目
            var listMenu = _studymenuService.GetListByFunc(m => m.ParentId == menuId).ToList();

            //获取当前栏目
            int id = Convert.ToInt32(lmid);
            var menu = _studymenuService.GetListByFunc(m => m.MenuId == id).FirstOrDefault();
            //找出需要的子栏目
            foreach (var item in listMenu)
            {
                if (menu.Pids.Contains("," + item.MenuId + ","))
                {
                    result += " " + item.MenuName;
                    break;
                }
            }

            return Json(new { msg = result });
        }

        #endregion

        #region 保持上次的状态

        public JsonResult AjaxGetLocus()
        {
            string pids = "";//用户上次看的视频的栏目的pids
            List<StudyLocus> list = new List<StudyLocus>();
            //获取登录的用户
            Member student = _memberService.GetLoginMember();
            if (student != null)
            {
                #region 用户的所有已完成的学习轨迹
                list = _studyLocusService.GetList(ls => ls.UserId == student.Id && ls.RecordTime != "");
                #endregion

                #region 用户上次最后看的视频的pids加上本栏目id

                //用户最后有效轨迹
                StudyLocus xxgj = list.OrderByDescending(x => x.EndTime).FirstOrDefault();

                if (xxgj != null)
                {
                    //获取用户最后一次有效栏目
                    StudyMenu column = _studymenuService.GetListByFunc(m => m.MenuId == xxgj.MenuId).FirstOrDefault();

                    if (column != null)
                    {
                        pids = column.Pids.Trim(',') + "," + column.MenuId;
                    }
                }
                #endregion
            }

            return Json(new { list = list, pids = pids });
        }

        #endregion

        #region 培训详情

        public ActionResult VideoStudyDetail(int? page)
        {
            ViewBag.myTabId = "3";//标示tab
            int pageIndex = page ?? 1;
            pageIndex -= 1;
            int pageSize = 10;
            //获取登录学员
            Member student = _memberService.GetLoginMember();
            if (student == null)
            {
                return RedirectToAction("MemberLogin", "Account");
            }

            var list = _studyLocusService.GetVMList(student.Id, pageIndex, pageSize);
            return View(list);
        }

        /// <summary>
        /// 获取当前登录用户的学习轨迹
        /// </summary>
        /// <returns></returns>
        public JsonResult GetLocusCount()
        {
            int Count = 0;
            int pageSize = 10;
            //获取登录学员
            Member student = _memberService.GetLoginMember();
            if (student != null)
            {
                //获取该学员的轨迹总数
                Count = _studyLocusService.GetList(sl => sl.UserId == student.Id).Count();
            }

            return Json(new { count = Count, pageSize = pageSize });
        }

        /// <summary>
        /// 理论培训详情 (学习轨迹) 分页方法
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public string GetLocusPageing(int? pageIndex)
        {
            int count = 0;
            pageIndex = pageIndex ?? 1;
            int pageSize = 10;

            //获取登录学员
            Member student = _memberService.GetLoginMember();
            if (student == null)
            {
                return "";
            }

            //获取该学员的所有学习轨迹
            var temp = _studyLocusService.GetList(sl => sl.UserId == student.Id);
            count = temp.Count;
            //获取分页数据
            List<StudyLocus> listxxgj = temp.Skip((pageIndex.Value - 1) * pageSize).Take(pageSize).ToList();
            //获取所有的视频
            List<StudyVideo> listVideo = _studyVideoService.GetList(sv => true);

            #region 拼html标签

            StringBuilder sbHtml = new StringBuilder();
            if (listxxgj != null)
            {
                if (listxxgj.Count > 0)
                {
                    // int xxsc = 0;//学习时长
                    var pxkm = "科目一";
                    int i = 0;
                    foreach (var x in listxxgj)
                    {
                        switch (x.MenuType)
                        {
                            case "1":
                                pxkm = "科目一";
                                break;
                            case "2":
                                pxkm = "科目二";
                                break;
                            case "3":
                                pxkm = "科目三";
                                break;
                        }
                        string videoFullName = listVideo.Where(v => v.Id == x.VideoId).FirstOrDefault().VideoTitle;
                        string videoName = videoFullName;
                        if (!string.IsNullOrEmpty(videoName))
                        {
                            if (videoName.Length > 8)
                            {
                                videoName = videoName.Substring(0, 8);
                            }
                        }
                        var cla = "";
                        i++;
                        if (i % 2 == 0) { cla = "class=bggray"; }
                        sbHtml.Append("<tr name=\"pxxqTr\" ");
                        sbHtml.Append(cla);
                        sbHtml.Append(">");
                        sbHtml.Append("<td>");
                        sbHtml.Append(student.Names);
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append(pxkm);
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td title=" + videoFullName + ">");
                        sbHtml.Append(videoName);
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append(x.StartTime);
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append(x.EndTime);
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append(x.RecordTime);
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append(x.IpAddress);
                        sbHtml.Append("</td>");
                        sbHtml.Append("</tr>");
                    }
                    for (int j = listxxgj.Count + 1; j < pageSize; j++)
                    {
                        var clas = "";
                        if (j % 2 == 0) { clas = "class=bggray"; }
                        sbHtml.Append("<tr name=\"pxxqTr\" ");
                        sbHtml.Append(clas);
                        sbHtml.Append(">");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("</tr>");
                    }
                }
                else
                {
                    for (int j = 0; j < pageSize; j++)
                    {
                        var clas = "";
                        if (j % 2 == 0) { clas = "class=bggray"; }
                        sbHtml.Append("<tr name=\"pxxqTr\" ");
                        sbHtml.Append(clas);
                        sbHtml.Append(">");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("<td>");
                        sbHtml.Append("");
                        sbHtml.Append("</td>");
                        sbHtml.Append("</tr>");
                    }
                }
            }

            #endregion

            return sbHtml.ToString();
        }

        #endregion

        #endregion

        public ActionResult videoplayer()
        {
            var v = Request.QueryString["v"];
            string url = "";
            if (v == null || string.IsNullOrEmpty(v) || v == "1")
            {
                url = "";
            }
            else
            {
                url = v;
            }
            ViewBag.Video = url;
            return View();
        }
    }
}
